//
//  BatchOperationView.swift
//  redbox
//
//  Created by ma c on 2025/9/11.
//

import SwiftUI

struct BatchOperationView: View {
    @EnvironmentObject var boxManager: BoxManager
    let activity: Activity
    @State private var selectedBoxes: Set<UUID> = []
    @State private var isRunning = false
    @State private var results: [UUID: String] = [:] // boxId: result
    @State private var showResults = false
    
    var body: some View {
        NavigationView {
            VStack {
                if isRunning {
                    // 执行中视图
                    ProgressView()
                        .scaleEffect(2)
                        .padding()
                    
                    Text("批量领取中...")
                        .font(.headline)
                        .padding()
                    
                    List {
                        ForEach(boxManager.getAllBoxes()) { box in
                            if selectedBoxes.contains(box.id) {
                                HStack {
                                    BoxRowView(box: box)
                                    Spacer()
                                    
                                    if let result = results[box.id] {
                                        Text(result)
                                            .foregroundColor(resultColor(for: result))
                                            .font(.caption)
                                    } else {
                                        ProgressView()
                                            .scaleEffect(0.5)
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // 选择界面
                    List {
                        Section(header: Text("选择要操作的盒子")) {
                            ForEach(boxManager.getAllBoxes()) { box in
                                BoxSelectionRow(
                                    box: box,
                                    isSelected: selectedBoxes.contains(box.id),
                                    onToggle: { toggleBoxSelection(box) }
                                )
                            }
                        }
                        
                        if showResults {
                            Section(header: Text("执行结果")) {
                                ForEach(boxManager.getAllBoxes()) { box in
                                    if let result = results[box.id] {
                                        HStack {
                                            BoxRowView(box: box)
                                            Spacer()
                                            Text(result)
                                                .foregroundColor(resultColor(for: result))
                                                .font(.caption)
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    Button(action: startBatchOperation) {
                        Text("开始批量领取")
                            .font(.headline)
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding()
                            .background(selectedBoxes.isEmpty ? Color.gray : Color.blue)
                            .cornerRadius(10)
                    }
                    .disabled(selectedBoxes.isEmpty)
                    .padding()
                }
            }
            .navigationTitle("批量操作")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    if !isRunning {
                        Button("全选") {
                            selectAllBoxes()
                        }
                    }
                }
            }
        }
    }
    
    private func toggleBoxSelection(_ box: Box) {
        if selectedBoxes.contains(box.id) {
            selectedBoxes.remove(box.id)
        } else {
            selectedBoxes.insert(box.id)
        }
    }
    
    private func selectAllBoxes() {
        selectedBoxes = Set(boxManager.getAllBoxes().map { $0.id })
    }
    
    private func startBatchOperation() {
        isRunning = true
        results.removeAll()
        showResults = true
        
        let selectedBoxObjects = boxManager.getAllBoxes().filter { selectedBoxes.contains($0.id) }
        
        BatchService.shared.claimActivity(activity, for: selectedBoxObjects) { box, result in
            results[box.id] = result
        } completion: {
            isRunning = false
        }
    }
    
    private func resultColor(for result: String) -> Color {
        switch result {
        case "成功": return .green
        case "失败", "网络超时": return .red
        case "已领取": return .orange
        default: return .gray
        }
    }
}

// 盒子选择行
struct BoxSelectionRow: View {
    let box: Box
    let isSelected: Bool
    let onToggle: () -> Void
    
    var body: some View {
        Button(action: onToggle) {
            HStack {
                BoxRowView(box: box)
                Spacer()
                
                if isSelected {
                    Image(systemName: "checkmark.circle.fill")
                        .foregroundColor(.blue)
                } else {
                    Image(systemName: "circle")
                        .foregroundColor(.gray)
                }
            }
            .contentShape(Rectangle())
        }
        .buttonStyle(PlainButtonStyle())
    }
}

// 盒子行视图
struct BoxRowView: View {
    let box: Box
    
    var body: some View {
        HStack {
            Image(systemName: "cube.fill")
                .font(.title3)
                .foregroundColor(box.isDefault ? .blue : .gray)
                .frame(width: 36, height: 36)
                .background(box.isDefault ? Color.blue.opacity(0.1) : Color.gray.opacity(0.1))
                .cornerRadius(8)
            
            VStack(alignment: .leading, spacing: 2) {
                Text(box.name)
                    .font(.headline)
                
                if box.isDefault {
                    Text("默认盒子")
                        .font(.caption)
                        .foregroundColor(.blue)
                }
            }
        }
    }
}

#Preview {
    BatchOperationView(activity: Activity.blackPrelude)
        .environmentObject(BoxManager.shared)
}